<template>
  <view>
    <!-- 公共组件-每个页面必须引入 -->
    <public-module></public-module>

<view class="u-p-l-20 u-p-r-20">
					<u--form class="u-m-b-20 numinput" label-position="left" label-width="40">
						<u-form-item label="名称">
						  <u--input v-model="goodsinfo.name" type="text" placeholder="商品名称"/>
						</u-form-item>
						
						  <view class="u-flex u-flex-middle">
							<view class="u-flex-8">
								<u-form-item label="价格">
									<u--input v-model="goodsinfo.price_market" type="digit" placeholder="设置价格"/>
								</u-form-item>
							</view>
							<view class="u-flex-4 u-p-l-20">
								<u-form-item label="单位" @click="showUnit = true">
								<u--input
									v-model="unit"
									disabled
									disabledColor="#ffffff"
									placeholder="个">
								</u--input>
								<u-icon slot="right" name="arrow-right"></u-icon>
								
								<u-action-sheet
									:show="showUnit"
									:actions="unit_list"
									title="请选择单位"
									@close="showUnit = false"
									@select="unitSelect">
								</u-action-sheet>
								</u-form-item>
							</view>
						  </view>
					<!--
					<view v-if="goodsinfo.use_sku==''||goodsinfo.use_sku==null||goodsinfo.use_sku==0)">
						<u-form-item label="代理价格" label-width="70">
						  <u-input v-model="goodsinfo.agency_price"  type="digit"/>
						  <text slot="right" style="font-size: 22rpx;color: #007AFF;" class="u-p-l-20">设置后代理可自动导入到其商店</text>
						</u-form-item>
						<view>代理价设置后，该商品的修改信息（销售价除外）都会同步到导入过此产品的代理商品。</view>
					</view>
					<view v-else>
						<u-form-item label="代理">
							<view>本产品为代理产品，代理价格：{{goodsinfo.agency_price}}元</view>
						</u-form-item>
					</view>
					-->
					
					<u-form-item  label="库存">
						  <u-input v-model="goodsinfo.stock_num"  type="number"/>
						  <text slot="right" style="font-size: 22rpx;color: #007AFF;" class="u-p-l-20">为0不限制</text>
					</u-form-item>

						<!--u-form-item  label="已售">
						  <u-input v-model="goodsinfo.soldnum"  type="input"/>
						  <text slot="right" style="font-size: 22rpx;color: #007AFF;" class="u-p-l-20">前台显示=设置数+订单数</text>
						</u-form-item-->

						<u-form-item label="介绍">
						  <editor id="editor" class="editor-container" placeholder="请输入内容" @input="getEditorContent" @ready="onEditorReady"></editor>
						</u-form-item>
				<u-form-item label="封面" borderBottom>
					<u-upload 
						:fileList="fileList1"
						@afterRead="afterRead"
						maxCount="1"
						@delete="deletePic"
						name="1"
						width="60"
						height="60">
					</u-upload>
				</u-form-item>
					
				<u-form-item label="图片" :borderBottom="false">
					<u-upload 
						:fileList="fileList2"
						@afterRead="afterRead"
						maxCount="5"
						@delete="deletePic"
						multiple
						name="2"
						width="60"
						height="60">
					</u-upload>
				</u-form-item>
			
			

				</u--form>
						<u-gap height="80"></u-gap>
				</view>
					<view class="flexbottom u-padding-20">
						<view><u-button type="primary" @click="goodssave()">保存</u-button></view>
						<u-gap height="30"></u-gap>
					</view>

  </view>
</template>


<script>
import { mapState, mapMutations } from "vuex";
import base from "@/config/baseUrl";
import { uploadFilePromise } from '@/plugins/upload/upload';
import { api_goods_item,api_goods_save } from '@/config/api.js';
export default {
  data() {
    return {
      goodsinfo: {
		  use_sku:'',
		  agency_price:'',
		  description:''
	  },
      hasLogin: false,
      loadStatus: "loadmore",
      loadstatus: false,
      fileList1:[],
	  fileList2:[],
	  showCategary:false,
	  showUnit:false,
	  shop_id:'',
	  unit_list:[
		  {name: '斤'},
		  {name: '个'},
		  {name: '份'},
		  {name: '包'},
		  {name: '盒'},
		  {name: '瓶'},
		  {name: '桶'},
		  {name: '次'},
		  {name: '箱'},
		  {name: '两'},
		  {name: '只'},
		  {name: '天'},
		  ],
		category:[],
	    category_id:0,
	    category_name:'',
	    select_Category:[],
	    unit_show:false,
		unit:''
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
   onLoad(options) {
	    this.goods_id = options.goods_id;
	    this.get_goodsinfo(this.goods_id);
		//this.category=this.siteInfo.goods_cate
		// this.select_Category[0]=this.category.map(item =>({
		// 	 label:item.category_name,
		// 	 id:item.category_id,
		//  }))
		//this.select_Category[0].splice(0,1)
  },

  methods: {
	  unit_confirm(e){
		  this.goodsinfo.unit=e[0].label
	  },
		showcategary(){
			this.showCategary = true;uni.hideKeyboard();
		},
		unitSelect(e){
			this.unit = e.name
		},

	goodssave(){
		var cover_id = ''
		if (this.fileList1.length>0){
			this.fileList1.map((item) => {
				cover_id=item.file_id
			})
		}
		let images = []
		this.fileList2.map((item) => {
			images.push({
				file_url:item.url,
				file_id:item.file_id
			})
		})
		api_goods_save({
			name:this.goodsinfo.name,
			unit:this.unit,
			content:this.goodsinfo.content,
			goods_id:this.goods_id,
			cover_id:cover_id,
			images_ids:JSON.stringify(images)
		}).then(res => {
				this.$tools.msg(
					`${this.goods_id == "" ? "添加" : "修改"}成功`
				);
				// let pages = getCurrentPages();
				// let beforePage = pages[pages.length - 2];
				// beforePage.$vm.reFresh = Math.random()
				setTimeout(() => {
					//uni.navigateBack(1);
					//this.$tools.routerTo("/pages/componentsC/shop/storemanage/goodsmanage",{shop_id:this.shop_id},'');
					let param = {shop_id:this.shop_id}
					uni.redirectTo({
						url:'/pages/componentsC/shop/storemanage/goodsmanage?query='+encodeURIComponent(JSON.stringify(param))
					})
					// uni.reLaunch({
					// 	url: 'pages/componentsC/shop/storemanage/goodsmanage'
					// })
				}, 400);
		}).catch((e)=>{});
	},

	get_goodsinfo(goods_id){
        api_goods_item({goods_id:goods_id}).then(res => {
			console.log(res)
			this.goodsinfo=res
			this.shop_id=res.shop_id
			this.onEditorReady()
			//this.unit=this.goodsinfo.unit
			if (res.cover_url!=''){
				this.fileList1.push({
					file_id:res.cover_id,
					url:res.cover_url,
				})
			}
			res.images.map((item) => {
				this.fileList2.push({
					file_id:item.file_id,
					url:item.file_url
				})
			})
        }).catch((e)=>{});
	},
	
    onEditorReady() {/////////////////////////初始化
        uni.createSelectorQuery().select('#editor').context((res) => {
                    var contentVal_1 = this.goodsinfo.content;
                    //将内容写入编辑器
                    this.editorCtx = res.context;
                    let EContent = {
                        html: contentVal_1
                    }
                    this.editorCtx.setContents(EContent); //设置富文本编辑器的内容
                }).exec()
            },
            getEditorContent(e) {/////////////////////////获取编辑器内容，当前页面都能获取到
                this.goodsinfo.content = e.detail.html;
            },
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await uploadFilePromise(lists[i].url,2)
					let item = this[`fileList${event.name}`][fileListLen]
					
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						file_id: result.file_id,
						url: result.file_url
					}))
					//this[`fileList${event.name}`][fileListLen].url=result
					fileListLen++
				}
			},
	
  },
};
</script>
<style lang="scss" scoped>
	.pre-box {
		align-items: center;
		justify-content: space-between;
		flex-wrap: wrap;
	}

	.pre-item {
		flex: 0 0 23%;
		border-radius: 10rpx;
		height: 260rpx;
		overflow: hidden;
		position: relative;
		margin-bottom: 20rpx;
		.u-icon{
			position: absolute;
			top:10rpx;
			right:10rpx;
		}
	}

	.pre-item-image {
		width: 100%;
		height: 260rpx;
	}
	.editor-container{
		border: solid 1px #cccccc;
		padding:5px
	}
</style>
